package com.ethjava.usdx;

import com.ethjava.utils.Environment;
import com.google.common.base.Strings;
import org.web3j.abi.TypeDecoder;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.http.HttpService;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutionException;

/**
 * 获取交易状态
 */
public class getTransactionStatus {

    private static Web3j web3j;

    public static void main(String[] args) {
        web3j = Web3j.build(new HttpService(Environment.RPC_URL));
        String txhash = "0xa5ba8aa2132ecd75347637a0d3c6fa0618763c26e100a554ab95804791f8291b";
//        String status = getStatus(txhash);
        parseInput();
    }


    /**
     *
     * @param txhash 交易hash
     * @return
     * 0失败 1成功
     */
    public static String getStatus(String txhash){
        String status = "0";
        try {
            EthGetTransactionReceipt ethGetTransactionReceipt = web3j.ethGetTransactionReceipt(txhash).sendAsync().get();
            String status1 = ethGetTransactionReceipt.getTransactionReceipt().get().getStatus();
            if(!Strings.isNullOrEmpty(status1)){
                status = status1.substring(2);
                System.out.println(status);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return status;
    }

    public static void parseInput(){
        String inputData = "0xa9059cbb0000000000000000000000006a2972e43f38f0b8217c119394d9b5a4cd116e9c000000000000000000000000000000000000000000000001bc16d674ec800000";
        String method = inputData.substring(0,10);
        String to = inputData.substring(10,74);
        String value = inputData.substring(74);
        Method refMethod = null;
        try {
            refMethod = TypeDecoder.class.getDeclaredMethod("decode",String.class,int.class,Class.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        refMethod.setAccessible(true);
        Address address = null;
        try {
            address = (Address)refMethod.invoke(null,to,0,Address.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        Uint256 amount = null;
        try {
            amount = (Uint256) refMethod.invoke(null,value,0,Uint256.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("method="+method+"\nto="+to+"\nvalue="+value+"\naddress="+address.getValue()+"\namount="+amount.getValue());
    }
}
